/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yiimanager Software LLC
 */
!function (global, top) {
    global.ym2App.controller("ym2.ctrl.file.manager", [
        "$scope",
        "$http",
        "Upload",
        "layui",
        "ym2",
        "ymSpinner",
        "swal",
        function ($scope, $http, Upload, layui, ym2, ymSpinner, swal) {
            "use strict";

            var topLayer = top.layui.layer;
            var topToastr = top.toastr;
            var topSweetAlert = top.sweetAlert;
            var topYmSpinner = top.ymSpinner;
            var $ = layui.jquery;
            var tree = layui.tree;
            var dropdown = layui.dropdown;

            var httpSuccessCode = ym2.getHttpSuccessCode();
            var httpFailureCode = ym2.getHttpFailureCode();
            var httpUnauthorizedCode = ym2.getHttpUnauthorizedCode();
            var ajaxIdentity = ym2.getHttpAjaxIdentity();
            var adminRouteLogin = ym2.getAdminRouteLogin();
            $scope.appThemeColor = ym2.getAppThemeColor();
            var pageNumber, perPageNumber, queryParams;

            //本地存储
            var KEY_CLASSIFY_ID = "CLASSIFY_ID";
            function setCache(key, value) {
                global.localStorage.setItem(key, value);
            }
            function getCache(key) {
                return global.localStorage.getItem(key);
            }
            function delCache(key) {
                global.localStorage.removeItem(key);
            }
            function clearCache() {
                global.localStorage.clear();
            }
            //合并查询参数
            function assignParams(param) {
                return Object.assign(queryParams || {}, param || {});
            }
            //渲染左侧菜单
            tree.render({
                elem: "#UploaderSide",
                id: "UploaderSide",
                data: [{
                    "title": "全部",
                    "id": 0,
                }],
                showLine: false, // 是否开启连接线
                onlyIconControl: true, // 是否仅允许节点左侧图标控制展开收缩
                click: function(obj){
                    var dataID = obj.data.id;
                    $scope._init(1, null, assignParams({ classify: dataID }));
                    $scope.$digest();
                }
            });
            $scope._getUploadSide = function () {
                $http.get("/__upload/classify").then(function (result) {
                    var data = result.data;
                    switch (data.code) {
                        case httpSuccessCode:
                            tree.reload("UploaderSide", {
                                data: data.data || [],
                            });
                            renderDropDown();
                            selectedThis();

                            break;
                        case httpFailureCode:
                            topToastr.error(data.msg);
                            break;
                        case httpUnauthorizedCode:
                            // 授权失效, 去登录
                            ym2.swal.timer(
                                topSweetAlert,
                                data.msg,
                                "自动跳转; <a href='" + adminRouteLogin + "' target='_top'>立即跳转<a/>",
                                function () {
                                    top.open(adminRouteLogin, "_self");
                                },
                                3000
                            );
                            break;
                        default:
                            topToastr.error(data.msg);
                    }

                }, function (error) {
                    topToastr.error(error.data || "系统错误, 发起请求失败!");
                    global.console.error(error);
                });
            };
            $scope._getUploadSide();
            //菜单右键工具
            function renderDropDown() {
                dropdown.render({
                    elem: ".layui-tree-entry",
                    trigger: "contextmenu",//右键点击
                    style: "width:150px",//定义宽度，默认自适应
                    data: [
                        {title: "添加子节点", id: "add"},
                        {title: "编辑当前节点", id: "edit"},
                        {title: "删除当前节点", id: "del"},
                    ],
                    click: function(obj, othis){
                        //当前分类ID
                        var dataID = this.elem.parent().data("id");

                        switch (obj.id) {
                            case "add"://新增
                                $scope._actionClassifyAdd(dataID);
                                break;
                            case "edit"://编辑
                                if (dataID == 0) {
                                    topToastr.info("该目录禁止编辑");
                                    return;
                                }

                                $scope._actionClassifyEdit(dataID);
                                break;
                            case "del"://删除
                                $scope._actionClassifyDelete(dataID);
                                break;
                        }
                    }
                });
            }
            //删除目录
            $scope._actionClassifyDelete = function (dataID) {
                ym2.swal.question(topSweetAlert, null, "删除后无法恢复!是否确认?", function (result) {
                    /* Read more about isConfirmed, isDenied below */
                    if (result.isConfirmed) {
                        // 发起ajax
                        // show loading
                        var flag = ymSpinner.show();
                        $http.post("/__upload/classify-delete", { id: dataID }).then(function (result) {
                            ymSpinner.hide(flag);

                            var data = result.data;
                            switch (data.code) {
                                case httpSuccessCode:
                                    ym2.swal.ok(topSweetAlert, data.msg);
                                    $scope._getUploadSide();
                                    break;
                                case httpFailureCode:
                                    topToastr.error(data.msg);
                                    break;
                                case httpUnauthorizedCode:
                                    // 授权失效, 去登录
                                    ym2.swal.timer(
                                        topSweetAlert,
                                        data.msg,
                                        "自动跳转; <a href='" + adminRouteLogin + "' target='_top'>立即跳转<a/>",
                                        function () {
                                            top.open(adminRouteLogin, "_self");
                                        },
                                        3000
                                    );
                                    break;
                                default:
                                    topToastr.error(data.msg);
                            }
                        }, function (error) {
                            ymSpinner.hide(flag);
                            ym2.swal.fail(topSweetAlert, error.data || "系统错误,发起请求失败!");
                            global.console.error(error);
                        });
                    }
                });
            };
            //编辑目录
            $scope._actionClassifyEdit = function (dataID) {
                var url = ym2.addUrlQueryParam("/__upload/classify-edit", {
                    id: dataID,
                });
                var layerScreenObj = ym2.layerScreenOptions("435px");
                var refererName = ym2.layerRefererWindowName("self");

                // iframe 模态框
                // var loadingFlag = topYmSpinner.show("加载中...");
                var layerCf = {
                    type: 2, // iframe
                    //skin: 'layui-layer-win10',
                    area: [layerScreenObj.width, "225px"],
                    title: "编辑名称",
                    shade: 0.3, // 遮罩透明度
                    shadeClose: false, // 点击遮罩区域，关闭弹层
                    closeBtn: 1,
                    maxmin: false, // 允许全屏最小化
                    anim: 0, // 0-6 的动画形式，-1 不开启
                    scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                    content: url,
                    success: function(layero, index, that){
                        // topYmSpinner.hide( loadingFlag );
                        // 弹层的最外层元素的 jQuery 对象
                        //console.log(layero);
                        // 弹层的索引值
                        //console.log(index);
                        // 弹层内部原型链中的 this --- 2.8+
                        //console.log(that);
                        // 获取iframe的窗口对象, 添加来源追踪
                        var iframeWin = top[layero.find("iframe")[0]["name"]];
                        iframeWin.__REFERER_WIN_NAME = refererName;
                    },
                };

                topLayer.open(layerCf);
            };
            //新增目录
            $scope._actionClassifyAdd = function (dataID) {
                var url = ym2.addUrlQueryParam("/__upload/classify-add", {
                    pid: dataID,
                });
                var layerScreenObj = ym2.layerScreenOptions("435px");
                var refererName = ym2.layerRefererWindowName("self");

                // iframe 模态框
                // var loadingFlag = topYmSpinner.show("加载中...");
                var layerCf = {
                    type: 2, // iframe
                    //skin: 'layui-layer-win10',
                    area: [layerScreenObj.width, "225px"],
                    title: "新增目录",
                    shade: 0.3, // 遮罩透明度
                    shadeClose: false, // 点击遮罩区域，关闭弹层
                    closeBtn: 1,
                    maxmin: false, // 允许全屏最小化
                    anim: 0, // 0-6 的动画形式，-1 不开启
                    scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                    content: url,
                    success: function(layero, index, that){
                        // topYmSpinner.hide( loadingFlag );
                        // 弹层的最外层元素的 jQuery 对象
                        //console.log(layero);
                        // 弹层的索引值
                        //console.log(index);
                        // 弹层内部原型链中的 this --- 2.8+
                        //console.log(that);
                        // 获取iframe的窗口对象, 添加来源追踪
                        var iframeWin = top[layero.find("iframe")[0]["name"]];
                        iframeWin.__REFERER_WIN_NAME = refererName;
                    },
                };

                topLayer.open(layerCf);
            };
            //左侧菜单UI脚本
            var UploadSideParentDom = $("#UploaderSide");
            UploadSideParentDom.on("click", ".layui-tree-entry", function (e) {
                UploadSideParentDom.find(".layui-tree-entry").removeClass("upload-active-this");
                $(this).addClass("upload-active-this");
                setCache(KEY_CLASSIFY_ID, $(this).parent().data("id") || 0);
            }).on("click", ".layui-tree-iconClick", function (e) {
                e.stopPropagation();
            });
            function selectedThis() {
                UploadSideParentDom.find("[data-id=\""+ (getCache(KEY_CLASSIFY_ID) || 0) +"\"]").children(".layui-tree-entry").addClass("upload-active-this");
            }
            //附件列表管理
            $scope._init = function (page, perPage, query) {
                var url = "/__upload/index";

                page = page || pageNumber || 1;
                perPage = perPage || perPageNumber || 15;
                query = query || queryParams || {};

                pageNumber = page;
                perPageNumber = perPage;
                queryParams = query;

                var param = {
                    page: page,
                    'per-page': perPage,
                };
                param[ajaxIdentity] = 1;

                /* 使用Jq的对象合并方案 */
                $.extend(param, query);

                var flag = ymSpinner.show();
                $http.get(ym2.addUrlQueryParam(url, param)).then(function (result) {
                    ymSpinner.hide(flag);

                    var data = result.data;
                    switch (data.code) {
                        case httpSuccessCode:
                            $scope.pageModel = data.data.page || "";
                            $scope.listData = data.data.list || [];
                            $scope.selectedSort = [];
                            break;
                        case httpFailureCode:
                            topToastr.error(data.msg);
                            break;
                        case httpUnauthorizedCode:
                            // 授权失效, 去登录
                            ym2.swal.timer(
                                topSweetAlert,
                                data.msg,
                                "自动跳转; <a href='" + adminRouteLogin + "' target='_top'>立即跳转<a/>",
                                function () {
                                    top.open(adminRouteLogin, "_self");
                                },
                                3000
                            );
                            break;
                        default:
                            topToastr.error(data.msg);
                    }

                }, function (error) {
                    ymSpinner.hide(flag);
                    topToastr.error(error.data || "系统错误, 发起请求失败!");
                    global.console.error(error);
                });
            };
            $scope._init(1, null, {
                classify: getCache(KEY_CLASSIFY_ID) || 0,
            });
            //分页点击方法
            $scope.actionLinkPage = function (page, limit) {
                $scope._init(page, limit);
            };
            //筛选点击方法
            $scope.actionSearch = function () {
                $scope._init(1, null, assignParams({
                    keyword: $scope.filterKeyword,
                }));
            };
            //清空筛选控件
            $scope.actionClearSearch = function () {
                $scope.filterKeyword = "";
                $scope._init(1, null, assignParams({
                    keyword: "",
                }));
            };
            //打开文件详情
            $scope.actionOpenDetail = function (url) {
                global.open(url, '', 'width=800,height=500,toolbar=0,left=500,top=200,location=0,menubar=0');
            };
            //编辑附件名称
            $scope.actionEdit = function (id) {
                var url = ym2.addUrlQueryParam("/__upload/file-edit", {
                    id: id,
                });
                var layerScreenObj = ym2.layerScreenOptions("435px");
                var refererName = ym2.layerRefererWindowName("self");

                // iframe 模态框
                // var loadingFlag = topYmSpinner.show("加载中...");
                var layerCf = {
                    type: 2, // iframe
                    //skin: 'layui-layer-win10',
                    area: [layerScreenObj.width, "225px"],
                    title: "编辑文件名",
                    shade: 0.3, // 遮罩透明度
                    shadeClose: false, // 点击遮罩区域，关闭弹层
                    closeBtn: 1,
                    maxmin: false, // 允许全屏最小化
                    anim: 0, // 0-6 的动画形式，-1 不开启
                    scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                    content: url,
                    success: function(layero, index, that){
                        // topYmSpinner.hide( loadingFlag );
                        // 弹层的最外层元素的 jQuery 对象
                        //console.log(layero);
                        // 弹层的索引值
                        //console.log(index);
                        // 弹层内部原型链中的 this --- 2.8+
                        //console.log(that);
                        // 获取iframe的窗口对象, 添加来源追踪
                        var iframeWin = top[layero.find("iframe")[0]["name"]];
                        iframeWin.__REFERER_WIN_NAME = refererName;
                    },
                };

                topLayer.open(layerCf);
            };
            //选中|取消
            $scope.actionToggle = function (id) {
                var map = $scope.selectedSort;
                var index = map.indexOf(id);
                if (index > -1) {
                    map.splice(index, 1);
                } else {
                    map.push(id);
                }
                $scope.selectedSort = map;
            };
            //文件上传表单
            $scope.actionForm = function (ev) {
                var url = ym2.addUrlQueryParam("/__upload/chunk", {
                    classify: getCache(KEY_CLASSIFY_ID) || 0,
                });
                var layerScreenObj = ym2.layerScreenOptions("675px");
                var refererName = ym2.layerRefererWindowName("self");

                // iframe 模态框
                // var loadingFlag = topYmSpinner.show("加载中...");
                var layerCf = {
                    type: 2, // iframe
                    //skin: 'layui-layer-win10',
                    area: [layerScreenObj.width, "729px"],
                    title: "上传文件",
                    shade: 0.3, // 遮罩透明度
                    shadeClose: false, // 点击遮罩区域，关闭弹层
                    closeBtn: 1,
                    maxmin: false, // 允许全屏最小化
                    anim: 0, // 0-6 的动画形式，-1 不开启
                    scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                    content: url,
                    success: function(layero, index, that){
                        // topYmSpinner.hide( loadingFlag );
                        // 弹层的最外层元素的 jQuery 对象
                        //console.log(layero);
                        // 弹层的索引值
                        //console.log(index);
                        // 弹层内部原型链中的 this --- 2.8+
                        //console.log(that);
                        // 获取iframe的窗口对象, 添加来源追踪
                        var iframeWin = top[layero.find("iframe")[0]["name"]];
                        iframeWin.__REFERER_WIN_NAME = refererName;
                    },
                    cancel: function(index, layero, that){
                        //刷新当前列表
                        $scope._init();
                        $scope.$digest();
                    }
                };

                topLayer.open(layerCf);
            };
            //删除文件
            $scope.actionFileDel = function (e) {
                var idMap = $scope.selectedSort || [];
                if (idMap.length <= 0) {
                    return;
                }

                ym2.swal.question(topSweetAlert, null, "删除后无法恢复!是否确认?", function (result) {
                    /* Read more about isConfirmed, isDenied below */
                    if (result.isConfirmed) {
                        // 发起ajax
                        // show loading
                        var flag = ymSpinner.show();
                        $http.post("/__upload/file-delete", { id: idMap }).then(function (result) {
                            ymSpinner.hide(flag);

                            var data = result.data;
                            switch (data.code) {
                                case httpSuccessCode:
                                    ym2.swal.ok(topSweetAlert, data.msg);
                                    $scope._init();
                                    break;
                                case httpFailureCode:
                                    topToastr.error(data.msg);
                                    break;
                                case httpUnauthorizedCode:
                                    // 授权失效, 去登录
                                    ym2.swal.timer(
                                        topSweetAlert,
                                        data.msg,
                                        "自动跳转; <a href='" + adminRouteLogin + "' target='_top'>立即跳转<a/>",
                                        function () {
                                            top.open(adminRouteLogin, "_self");
                                        },
                                        3000
                                    );
                                    break;
                                default:
                                    topToastr.error(data.msg);
                            }
                        }, function (error) {
                            ymSpinner.hide(flag);
                            ym2.swal.fail(topSweetAlert, error.data || "系统错误,发起请求失败!");
                            global.console.error(error);
                        });
                    }
                });
            };
            //转移文件
            $scope.actionFileTransfer = function (e) {
                var idMap = $scope.selectedSort || [];
                if (idMap.length <= 0) {
                    return;
                }

                var url = ym2.addUrlQueryParam("/__upload/file-transfer", {
                    currentClassify: getCache(KEY_CLASSIFY_ID) || 0,
                    idMap: idMap,
                });
                var layerScreenObj = ym2.layerScreenOptions("435px");
                var refererName = ym2.layerRefererWindowName("self");

                // iframe 模态框
                // var loadingFlag = topYmSpinner.show("加载中...");
                var layerCf = {
                    type: 2, // iframe
                    //skin: 'layui-layer-win10',
                    area: [layerScreenObj.width, "365px"],
                    title: "转移文件",
                    shade: 0.3, // 遮罩透明度
                    shadeClose: false, // 点击遮罩区域，关闭弹层
                    closeBtn: 1,
                    maxmin: false, // 允许全屏最小化
                    anim: 0, // 0-6 的动画形式，-1 不开启
                    scrollbar: false, // 打开弹层时，是否允许浏览器出现滚动条。
                    content: url,
                    success: function(layero, index, that){
                        // topYmSpinner.hide( loadingFlag );
                        // 弹层的最外层元素的 jQuery 对象
                        //console.log(layero);
                        // 弹层的索引值
                        //console.log(index);
                        // 弹层内部原型链中的 this --- 2.8+
                        //console.log(that);
                        // 获取iframe的窗口对象, 添加来源追踪
                        var iframeWin = top[layero.find("iframe")[0]["name"]];
                        iframeWin.__REFERER_WIN_NAME = refererName;
                    },
                };

                topLayer.open(layerCf);
            };
            //使用选中文件
            $scope.actionUseSelectedFiles = function () {
                var selected = $scope._getSelectedItem();
                if (!selected.length) {
                    return;
                }

                var callback = global.onFileSelected;
                if (!callback || ym2.typeOf(callback) !== "function") {
                    topToastr.info("未检测到onFileSelected事件回调!");
                    return;
                }

                var result = callback.call(this, $scope._getSelectedItem());
                if (result === false) {
                    return;
                }

                var index = topLayer.getFrameIndex(global.name);
                topLayer.close(index);
            };
            //获取选中项
            $scope._getSelectedItem = function () {
                var selectedIDs = $scope.selectedSort || [];
                var listData = $scope.listData;
                if (!selectedIDs.length) {
                    return [];
                }

                var result = [];
                var index;
                for (var i = 0; i < listData.length; i++)  {
                    index = selectedIDs.indexOf(listData[i].id);
                    if (index > -1) {
                        result[index] = listData[i];
                    }
                }

                return result;
            };
            //外部回调
            global.ym2CbkExport = {
                classifyView: $scope._getUploadSide,
                fileView: $scope._init,
            };

        }
    ]);
}(window, top);